package com.fragment;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.act.Answer_ListAct;
import com.act.BindMobileAct;
import com.act.Mine_FocusUsersAct;
import com.act.Mine_FriendAct;
import com.act.LoginAct;
import com.act.LoginUserInfo;
import com.act.MyApplication;
import com.act.Mine_CollectsAct;
import com.act.Question_ListAct;
import com.act.UserInfoAct;
import com.bean.UserInfo;
import com.common.Constant;
import com.common.HttpClient;
import com.common.LocalFileHelper;
import com.control.UserControl;
import com.easemob.chat.EMChatManager;
import com.emchat.DbOpenHelper;
import com.umeng.analytics.MobclickAgent;
import com.xike.kyt.R;
import com.loopj.android.http.TextHttpResponseHandler;
import com.mUI.MyProgressDialog;
import com.mUI.MyToast;
import com.xike.util.MLog;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class MineFragment extends BaseFragment implements OnClickListener {
	private static final int REQUSET_CODE_TO_USERINFO = 1;
	private static final int REQUSET_CODE_TO_BINDPHONENUM = 2;

	ImageView img_avator;
	TextView tv_userName, tv_summary, tv_questionNum, tv_answerNum, tv_collectNum;
	RelativeLayout layout_userInfo;
	LinearLayout layout_myQuestion, layout_myAnswer, layout_myCollect;
	TextView tv_myFriend, tv_myFocusQuestion, tv_myFocusPerson, tv_bindPhoneNum, tv_bindedNum;
	// TextView tv_draftBox;
	UserInfo userInfo;
	boolean httpRequestLock = false;
	boolean isCreate = false;
	boolean isRefresh = false;

	String strNewNickName;
	Bitmap newUserAvator;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		client = new HttpClient();
		mToast = new MyToast();
		isCreate = true;
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_mine, null);
		initViews(view);
		serviceGetUserInfo();
		return view;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUSET_CODE_TO_USERINFO && resultCode > 0) {
			if (data != null && data.getExtras() != null) {
				if (data.getExtras().containsKey("newNickName")) {
					strNewNickName = data.getExtras().getString("newNickName");
					tv_userName.setText(strNewNickName);
				}
				if (data.getExtras().containsKey("newAvator")) {
					newUserAvator = (Bitmap) data.getExtras().get("newAvator");
					if (newUserAvator != null && newUserAvator.getWidth() > 0) {
						img_avator.setImageBitmap(MyUtil.getRoundedCornerBitmap(newUserAvator));
					}
				}
			}
		} else if (requestCode == REQUSET_CODE_TO_BINDPHONENUM && resultCode > 0) {
			MyUtil.setTextViewText(tv_bindedNum, UserControl.getLoginUserBindMobile(), View.INVISIBLE, "");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initViews(View view) {

		img_avator = (ImageView) view.findViewById(R.id.mine_img_userImg);

		tv_userName = (TextView) view.findViewById(R.id.mine_tv_userName);
		tv_summary = (TextView) view.findViewById(R.id.mine_tv_summary);
		tv_questionNum = (TextView) view.findViewById(R.id.mine_tv_questionNum);
		tv_answerNum = (TextView) view.findViewById(R.id.mine_tv_answerNum);
		tv_collectNum = (TextView) view.findViewById(R.id.mine_tv_collectNum);

		layout_userInfo = (RelativeLayout) view.findViewById(R.id.mine_layout_userInfo);
		layout_myQuestion = (LinearLayout) view.findViewById(R.id.mine_layout_myQuestion);
		layout_myAnswer = (LinearLayout) view.findViewById(R.id.mine_layout_myAnswer);
		layout_myCollect = (LinearLayout) view.findViewById(R.id.mine_layout_myCollect);

		tv_myFriend = (TextView) view.findViewById(R.id.mine_tv_myFriend);
		tv_myFocusQuestion = (TextView) view.findViewById(R.id.mine_tv_myFocusQuestion);
		tv_myFocusPerson = (TextView) view.findViewById(R.id.mine_tv_myFocusPerson);
		// tv_draftBox = (TextView) view.findViewById(R.id.mine_tv_draftBox);
		tv_bindPhoneNum = (TextView) view.findViewById(R.id.mine_tv_bindPhoneNum);
		tv_bindedNum = (TextView) view.findViewById(R.id.mine_tv_bindedNum);

		view.findViewById(R.id.mine_btn_logout).setOnClickListener(this);

	}

	private void updateViews() {
		if (getActivity() == null) {
			return;
		}
		layout_userInfo.setOnClickListener(this);
		layout_myQuestion.setOnClickListener(this);
		layout_myAnswer.setOnClickListener(this);
		layout_myCollect.setOnClickListener(this);

		tv_myFriend.setOnClickListener(this);
		tv_myFocusQuestion.setOnClickListener(this);
		tv_myFocusPerson.setOnClickListener(this);
		// tv_draftBox.setOnClickListener(this);

		tv_bindPhoneNum.setOnClickListener(this);

		MyUtil.setTextViewText(tv_userName, userInfo.getShow_name(), View.INVISIBLE, "");
		MyUtil.setTextViewText(tv_summary, userInfo.getSummary(), View.INVISIBLE, "");
		MyUtil.setTextViewText(tv_questionNum, String.valueOf(userInfo.getQuestion_nums()), 0, "0");
		MyUtil.setTextViewText(tv_answerNum, String.valueOf(userInfo.getAnswer_nums()), 0, "0");
		MyUtil.setTextViewText(tv_collectNum, String.valueOf(userInfo.getCollection_nums()), 0, "0");

		MyUtil.setTextViewText(tv_bindedNum, UserControl.getLoginUserBindMobile(), View.INVISIBLE, "");

		BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
		MyUtil.displayImageView(getActivity(), userInfo.getAvator(), img_avator, bd.getBitmap(), true);
	}

	private void serviceGetUserInfo() {
		if (httpRequestLock) {
			return;
		}

		httpRequestLock = true;

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_USER_INFO, params);
		// // 本地缓存
		// if (LocalFileHelper.getInstance(getActivity()).fileIsExited(strUrl)) {
		// UserInfo result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), UserInfo.class);
		// dealRequestResult(result);
		// return;
		// }
		// 网络请求
		if (isCreate) {
			MyProgressDialog.show(getActivity(), true);
		}

		client.get(getActivity(), strUrl, new TextHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				UserInfo result = gson.fromJson(responseString, UserInfo.class);
				dealRequestResult(result);
				MLog.e("serviceGetUserInfo", "result:" + responseString);
				httpRequestLock = false;
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				if (isCreate) {
					MyProgressDialog.cancle();
					mToast.showToast(getActivity(), getString(R.string.net_error));
				}
				httpRequestLock = false;
			}
		});
		isCreate = false;
	}

	private void dealRequestResult(UserInfo result) {

		MyProgressDialog.cancle();
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				userInfo = result;
				updateViews();
				UserControl.updateUserInfo(userInfo);
			} else {
				mToast.showToast(getActivity(), result.getError_description());
			}
		} else {
			mToast.showToast(getActivity(), getString(R.string.net_error));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mine_layout_userInfo: // 用户信息
			Intent it_userInfo = new Intent(getActivity(), LoginUserInfo.class);
			it_userInfo.putExtra("userNickName", StringUtil.isNotNull(strNewNickName) ? strNewNickName : userInfo.getNick_name());
			if (newUserAvator != null && newUserAvator.getWidth() > 0) {
				it_userInfo.putExtra("userAvatorBitmap", newUserAvator);
			} else {
				it_userInfo.putExtra("userAvator", userInfo.getAvator());
			}
			startActivityForResult(it_userInfo, REQUSET_CODE_TO_USERINFO);
			break;
		case R.id.mine_layout_myQuestion: // 我的问题
			Intent it_questionList = new Intent(getActivity(), Question_ListAct.class);
			it_questionList.putExtra("user_id", userInfo.getId());
			startActivity(it_questionList);
			break;
		case R.id.mine_layout_myAnswer:// 我的答案
			Intent it_answerList = new Intent(getActivity(), Answer_ListAct.class);
			it_answerList.putExtra("user_id", userInfo.getId());
			startActivity(it_answerList);
			break;
		case R.id.mine_layout_myCollect:// 我的收藏
			startActivity(new Intent(getActivity(), Mine_CollectsAct.class));
			break;
		case R.id.mine_tv_myFriend: // 我的好友
			startActivity(new Intent(getActivity(), Mine_FriendAct.class));
			break;
		case R.id.mine_tv_myFocusQuestion:// 关注的问题
			Intent it_focusQuestionList = new Intent(getActivity(), Question_ListAct.class);
			it_focusQuestionList.putExtra("showFocus", true);
			startActivity(it_focusQuestionList);
			break;
		case R.id.mine_tv_myFocusPerson:// 关注的人
			startActivity(new Intent(getActivity(), Mine_FocusUsersAct.class));
			break;
		// case R.id.mine_tv_draftBox:// 草稿箱
		//
		// break;
		case R.id.mine_tv_bindPhoneNum:// 草稿箱
			Intent it_bindPhoneNum = new Intent(getActivity(), BindMobileAct.class);
			startActivityForResult(it_bindPhoneNum, REQUSET_CODE_TO_BINDPHONENUM);
			break;
		case R.id.mine_btn_logout:// 退出
			UserControl.logout();
			MyApplication.getInstance().logout();

			Intent it = new Intent(getActivity(), LoginAct.class);
			it.putExtra("isNewLogin", true);
			startActivity(it);
			getActivity().finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			newUserAvator = null;
			serviceGetUserInfo();
		}
		super.onHiddenChanged(hidden);
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("MineFragment"); // 统计页面
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("MineFragment");
	}
}
